package com.liu.vueblog.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.vueblog.common.dto.LoginDto;
import com.liu.vueblog.common.lang.Result;
import com.liu.vueblog.entity.User;
import com.liu.vueblog.service.UserService;
import com.liu.vueblog.utils.JwtUtils;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@RestController
public class AccountController {

    @Resource
    UserService userService;
    @Resource
    JwtUtils jwtUtils;

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){
        QueryWrapper<User> username = new QueryWrapper<User>().eq("username", loginDto.getUsername());
        User user = userService.getOne(username);
        Assert.notNull(user, "用户名不存在");
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return Result.fail("密码不正确");
        }
        String jwt = jwtUtils.generateToken(user.getId());
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email",user.getEmail())
                .map()
        );
    }

    @RequiresAuthentication
    @RequestMapping(path = "/logout", method = RequestMethod.GET)
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return Result.success(null);
    }
}
